/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.web;

import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.security.action.Secure;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xptracker.domain.EmailConfiguration;
import org.xptracker.persistence.PersistenceManager;

@UrlBinding("/EmailConfiguration.action")
@Secure(roles="admin")
public class EmailConfigurationActionBean extends StandardActionBean {
  Log logger = LogFactory.getLog(EmailConfigurationActionBean.class);

  private EmailConfiguration emailConfiguration;
  private boolean saveEnabled;

  @DefaultHandler
  public Resolution load() {
    return new ForwardResolution("/admin/emailConfiguration.jsp");
  }

  @Before(stages=LifecycleStage.BindingAndValidation)
  public void setupConfig() {
    emailConfiguration = loadConfig();
    saveEnabled = true;
  }

  private EmailConfiguration loadConfig() {
    return domain.loadEmailConfiguration();
  }

  @HandlesEvent("Save")
  public Resolution save() {
    persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<Object>() {
      public Object doUpdate(PersistenceManager.UpdateReceiver receiver) {
        EmailConfiguration toUpdate = loadConfig();
        toUpdate.setEnabled(emailConfiguration.isEnabled());
        toUpdate.setUsername(emailConfiguration.getUsername());
        toUpdate.setPassword(emailConfiguration.getPassword());
        toUpdate.setSmtpHost(emailConfiguration.getSmtpHost());
        receiver.update(toUpdate);
        return null;
      }
    });
    getContext().getMessages().add(new SimpleMessage("Configuration changes saved."));
    return new RedirectResolution(EmailConfigurationActionBean.class).flash(this);
  }

  public EmailConfiguration getEmailConfiguration() {
    return emailConfiguration;
  }

  public void setEmailConfiguration(EmailConfiguration emailConfiguration) {
    this.emailConfiguration = emailConfiguration;
  }

  public boolean isSaveEnabled() {
    return saveEnabled;
  }

  public void setSaveEnabled(boolean saveEnabled) {
    this.saveEnabled = saveEnabled;
  }
}
